/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.century.sjt.EMChat.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMContactManager;
import com.century.sjt.EMChat.widget.EaseAlertDialog;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * 查找添加好友
 */
public class AddContactActivity extends BaseActivity {
    private EditText editText;
    private LinearLayout searchedUserLayout;
    private TextView idText,tvName;
    private ImageView avatar;
    private InputMethodManager inputMethodManager;
    private String toAddUsername;
    private ProgressDialog progressDialog;

    private EditText etTipString;
    private SjtTitleBar titleBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_contact);
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.tab_add_friend));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightIconResourc(getString(R.string.btn_search));
        titleBar.setRightIconSize();
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchContact();
            }
        });
        editText = (EditText) findViewById(R.id.edit_note);
        String strUserName = getResources().getString(R.string.enter_your_phone_number);
        editText.setHint(strUserName);
        searchedUserLayout = (LinearLayout) findViewById(R.id.ll_user);
        idText = (TextView) findViewById(R.id.id);
        tvName = (TextView) findViewById(R.id.name);
        avatar = (ImageView) findViewById(R.id.avatar);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

        //软键盘设置
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“GO”键*/
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }

//                    edittext.setText("success");
//                    webview.loadUrl(URL);
                    searchContact();
                    return true;
                }
                return false;
            }
        });
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }


    /**
     * 查找contact
     * @param
     */
    public void searchContact() {
            final String name = editText.getText().toString();
            toAddUsername = name;
            MobileUserDetail(toAddUsername);
//            if (getString(R.string.button_search).equals(saveText)) {
//                toAddUsername = name;
////                if (TextUtils.isEmpty(name)) {
////                    new EaseAlertDialog(this, R.string.Please_enter_a_username).show();
////                    return;
////                }
////
////                // TODO 从服务器获取此contact,如果不存在提示不存在此用户
////
////                //服务器存在此用户，显示此用户和添加按钮
////                searchedUserLayout.setVisibility(View.VISIBLE);
////                nameText.setText(toAddUsername);
//
//
//            }

    }

    /**
     *  添加contact
     * @param view
     */
    public void addContact(View view) {

        View layout = LayoutInflater.from(AddContactActivity.this).inflate(R.layout.alert_dialog_edittext, null);
        etTipString = (EditText) layout.findViewById(R.id.et_content);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getResources().getString(R.string.text_add_friend_hint));
//			builder.setMessage("您还未实名认证，是否前去实名认证？");
        builder.setView(layout);
        builder.setPositiveButton(getResources().getString(R.string.text_sure), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
                String tipString = etTipString.getText().toString().trim();
                //添加好友
                addContactEvent(tipString);

            }
        });
        builder.setNegativeButton(getResources().getString(R.string.text_cancle), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    private void addContactEvent(final String tipString) {
        if (EMChatManager.getInstance().getCurrentUser().equals(toAddUsername)) {
            new EaseAlertDialog(this, R.string.not_add_myself).show();
            return;
        }

        if (SjtHelper.getInstance().getContactList().containsKey(toAddUsername)) {
            //提示已在好友列表中(在黑名单列表里)，无需添加
            if (EMContactManager.getInstance().getBlackListUsernames().contains(toAddUsername)) {
//                new EaseAlertDialog(this, R.string.user_already_in_contactlist).show();
                return;
            }
            new EaseAlertDialog(this, R.string.This_user_is_already_your_friend).show();
            return;
        }

        progressDialog = new ProgressDialog(this);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {

                try {
                    String s;
                    s = getResources().getString(R.string.Add_a_friend);
                    if (!tipString.equals("")) {
                        s = tipString;
                    }
                    EMContactManager.getInstance().addContact(toAddUsername, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(R.string.send_successful);
                            Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    public void back(View v) {
        finish();
    }
    private void MobileUserDetail(final String mobile) {
        //显示Progress Dialog
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), AddContactActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.MobileUserDetail, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.log("保存用户信息接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        if (data.has("userId")){
                            toAddUsername = data.getString("userId");
                            String phome=data.getString("mobile");
                            String name =data.getString("nickName");
                            searchedUserLayout.setVisibility(View.VISIBLE);
                            idText.setText(phome);
                            tvName.setText(name);
//                            ImageHost_Small
                            String ImgURL = Constant.ImageHost_Small+data.getString("image");
                            Glide.with(AddContactActivity.this).load(ImgURL).into(avatar);
                        }else {
                            TipUtil.showToast(getResources().getString(R.string.text_user_dnt_exits), AddContactActivity.this, 1);
                        }



                    } else {//失败
                        TipUtil.showToast(message, AddContactActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), AddContactActivity.this, 1);
                }
                TipUtil.closeProgressDialog();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), AddContactActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
//
                map.put("loginId", userId);
                map.put("mobile",mobile);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
//                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }



}
